<template>
  <NavBar title="搜题记录" color="#fff" colorText="#333" brg="#f8f8f8">
  <view class="search-history-container">
    
    <!-- 标签页 -->
    <view class="tab-container">
      <view 
        class="tab-item left" 
        :class="{ active: activeTab === 'all' }"
        @click="switchTab('all')"
      >
        <text class="tab-text">全部</text>
        <view class="tab-indicator tab-indicator-left" v-if="activeTab === 'all'"></view>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'success' }"
        @click="switchTab('success')"
      >
        <text class="tab-text">成功</text>
        <view class="tab-indicator" v-if="activeTab === 'success'"></view>
      </view>
      <view 
        class="tab-item right" 
        :class="{ active: activeTab === 'failed' }"
        @click="switchTab('failed')"
      >
        <text class="tab-text">失败</text>
        <view class="tab-indicator tab-indicator-right" v-if="activeTab === 'failed'"></view>
      </view>
    </view>
    
    <!-- 记录列表 -->
    <scroll-view
      class="record-list-container"
      scroll-y="true"
      @scrolltolower="onScrollToLower"
      lower-threshold="100"
    >
      <view class="record-list" v-if="filteredRecords.length > 0">
        <!-- 记录列表内容 -->
        <view
          class="record-item"
          v-for="(record, index) in filteredRecords"
          :key="record.id || index"
        >
          <view class="record-image" @click="previewImage(record.image_url)">
            <image
              class="search-image"
              :src="record.image_url || '/static/default-search.png'"
              mode="aspectFill"
            />
          </view>
          <view class="record-content">
            <text class="record-desc">{{ record.description }}</text>
            <text class="record-time">{{ record.time }}</text>
          </view>
          <view class="record-divider" v-if="index < filteredRecords.length - 1"></view>
        </view>
        
        <!-- 加载状态 -->
        <view class="load-more" v-if="loading || hasMore">
          <view v-if="loading" class="loading-text">
            <text>加载中...</text>
          </view>
          <view v-else-if="hasMore" class="load-more-text">
            <text>上拉加载更多</text>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="!loading && filteredRecords.length === 0">
        <image class="empty-icon" src="/static/empty.png" mode="widthFix"></image>
        <text class="empty-text">暂无记录</text>
      </view>
    </scroll-view>
  </view>
  </NavBar>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getToken, isLoggedIn } from '../../utils/user.js'
import { SOLVE_API } from '../../config/api.js'

// 响应式数据
const activeTab = ref('all')
const records = ref([])
const loading = ref(false)
const error = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const hasMore = ref(false)
const total = ref(0)

// 获取搜题记录
const fetchRecords = async (reset = false) => {
  // 检查登录状态
  const loginStatus = isLoggedIn()
  if (!loginStatus) {
    console.log('用户未登录，不请求搜题记录接口')
    records.value = []
    return
  }

  if (loading.value) return

  try {
    loading.value = true
    error.value = ''

    if (reset) {
      currentPage.value = 1
      records.value = []
      hasMore.value = true
    }

    const token = getToken()
    if (!token) {
      throw new Error('未找到用户token，请重新登录')
    }

    // 构建请求参数
    const params = {
      page: currentPage.value,
      page_size: pageSize.value
    }

    // 根据标签页添加状态筛选
    if (activeTab.value === 'success') {
      params.solve_status = 1 // 成功
    } else if (activeTab.value === 'failed') {
      params.solve_status = 2 // 失败
    }
    // 全部不传solve_status参数

    // 构建查询字符串
    const queryString = Object.keys(params)
      .filter(key => params[key] !== undefined)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')

    const response = await uni.request({
      url: `${SOLVE_API.LOGS}?${queryString}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })

    console.log('搜题记录API响应:', response)

    if (response.statusCode === 200 && response.data.code === 200) {
      const responseData = response.data.data || {}
      const newData = responseData.list || []

      // 更新总数据量和分页信息
      total.value = responseData.total || 0
      hasMore.value = responseData.has_more || false

      // 处理API返回的数据，转换为页面需要的格式
      const processedData = newData.map(record => ({
        id: record.id,
        description: record.status_name || '未知状态',
        time: formatTime(record.created_at),
        image_url: record.image_url,
        status: record.solve_status,
        error_message: record.error_message
      }))

      if (reset) {
        records.value = processedData
        currentPage.value = 1
      } else {
        records.value = [...records.value, ...processedData]
      }

      console.log('转换后的搜题记录数据:', records.value)
    } else {
      const errorMessage = response.data?.data?.error_message || response.data?.error_message || response.data?.message || '获取搜题记录失败'
      throw new Error(errorMessage)
    }

  } catch (err) {
    console.error('获取搜题记录失败:', err)
    error.value = err.message || '获取记录失败，请重试'
    uni.showToast({
      title: error.value,
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}



// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''

  try {
    const date = new Date(timeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('时间格式化失败:', error)
    return timeStr
  }
}

// 计算属性 - 根据当前标签过滤记录
const filteredRecords = computed(() => {
  if (activeTab.value === 'all') {
    return records.value
  } else if (activeTab.value === 'success') {
    return records.value.filter(record => record.status === 1)
  } else if (activeTab.value === 'failed') {
    return records.value.filter(record => record.status === 2)
  }
  return records.value
})

// 方法
const goBack = () => {
  uni.navigateBack()
}

const switchTab = (tab) => {
  activeTab.value = tab
  // 切换标签页时重新加载数据
  fetchRecords(true)
}

// 预览图片
const previewImage = (imageUrl) => {
  if (!imageUrl || imageUrl === '/static/default-search.png') {
    uni.showToast({
      title: '暂无图片可预览',
      icon: 'none'
    })
    return
  }

  uni.previewImage({
    urls: [imageUrl],
    current: imageUrl,
    fail: (error) => {
      console.error('图片预览失败:', error)
      uni.showToast({
        title: '图片预览失败',
        icon: 'error'
      })
    }
  })
}

// 滚动到底部加载更多
const onScrollToLower = () => {
  console.log('滚动到底部，检查是否需要加载更多数据')

  // 如果正在加载或没有更多数据，则不执行
  if (loading.value || !hasMore.value) {
    console.log('跳过加载：', { loading: loading.value, hasMore: hasMore.value })
    return
  }

  console.log('开始加载下一页数据，当前页：', currentPage.value)

  // 增加页码并加载下一页
  currentPage.value++
  fetchRecords(false)
}

// 页面挂载时获取数据
onMounted(() => {
  fetchRecords(true)
})
</script>

<style scoped>
.search-history-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #C2DDFF 0%, #FFFFFF 100%);
  border-radius: 0rpx 0rpx 0rpx 0rpx;
  padding-top:160rpx ;
}

/* 标签页 */
.tab-container {
  display: flex;
  padding: 0 40rpx;
  margin-bottom: 10rpx;
  padding-top: 20rpx;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
  position: relative;
}

.tab-text {
  font-size: 32rpx;
  font-weight: 500;
  color: #999999;
  transition: color 0.3s ease;
}

.tab-item.active .tab-text {
  color: #000000;
}

.tab-indicator {
  width: 40rpx;
  height: 6rpx;
  background: #8B5CF6;
  border-radius: 3rpx;
  margin-top: 8rpx;
}

.left {
  align-items: flex-start !important;
}

.right {
  align-items: flex-end !important;
}

.tab-indicator-left {
  margin-left: 8rpx;
}

.tab-indicator-right {
  margin-right: 12rpx;
}

/* 记录列表容器 */
.record-list-container {
  height: calc(100vh - 200rpx);
  margin: 0 30rpx;
  background: #FFFFFF;
  border-radius: 20rpx 20rpx 20rpx 20rpx;
  width: 92%;
}

/* 记录列表 */
.record-list {
  padding: 0 40rpx;
  min-height: 80%;
}

.record-item {
  position: relative;
  padding: 30rpx 0;
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
}

.record-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  overflow: hidden;
  flex-shrink: 0;
}

.search-image {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.record-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  padding-top: 10rpx;
}

.record-desc {
  font-size: 32rpx;
  font-weight: 500;
  color: #000000;
  line-height: 1.4;
}

.record-time {
  font-size: 24rpx;
  color: #999999;
}

.record-divider {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1rpx;
  background: repeating-linear-gradient(
    to right,
    #8B8B8B 0,
    #8B8B8B 8rpx,
    transparent 8rpx,
    transparent 16rpx
  );
}

/* 加载更多样式 */
.load-more {
  padding: 30rpx 0;
  text-align: center;
}

.loading-text {
  color: #999999;
  font-size: 28rpx;
}

.load-more-text {
  color: #CCCCCC;
  font-size: 28rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 120rpx 0;
  gap: 20rpx;
}

.empty-icon {
  width: 146rpx;
  height: 200rpx;
  margin-top: 250rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}

.retry-btn {
  font-size: 26rpx;
  color: #8B5CF6;
  padding: 10rpx 20rpx;
  border: 1rpx solid #8B5CF6;
  border-radius: 20rpx;
  cursor: pointer;
}

.retry-btn:active {
  opacity: 0.7;
}
</style>
